package org.dromara.solonplugins.job.impl;

import org.dromara.solonplugins.job.IJobHandler;
import org.dromara.solonplugins.job.IJobSource;
import org.dromara.solonplugins.job.JobInfo;
import org.dromara.solonplugins.job.annotation.JobHandler;
import org.noear.solon.Solon;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 默认的Job来源实现（从注解{@link JobHandler}加载Job）
 *
 * @author: aoshiguchen
 */
public class DefaultJobSource implements IJobSource {

	/**
	 * 获取所有job列表
	 * @return Job列表
	 */
	@Override
	public List<JobInfo> sourceList() {
		List<IJobHandler> jobHandlerList = Solon.context().getBeansOfType(IJobHandler.class);
		if (null == jobHandlerList || jobHandlerList.isEmpty()) {
			return Collections.emptyList();
		}
		List<JobInfo> jobInfoList = new ArrayList<>();
		for (IJobHandler jobHandler : jobHandlerList) {
			JobHandler handler = jobHandler.getClass().getAnnotation(JobHandler.class);
			if (null == handler || null == handler.name() || handler.name().length() == 0 ||
					null == handler.cron() || handler.cron().length() == 0) {
				continue;
			}
			jobInfoList.add(new JobInfo()
				.setId(handler.name())
				.setName(handler.name())
				.setDesc(handler.desc())
				.setCron(handler.cron())
				.setParam(handler.param())
				.setEnable(true)
				.setJobHandler(jobHandler)
			);
		}
		return jobInfoList;
	}

}
